/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { X2DBeta } = require("../graphics/X2DInterface");
const { XStat } = require("../XStat");
const { TextEditor } = require("../XTextInput");
const { XButton } = require("./XButton");

class XInput extends XButton {
    constructor(options = null) {
        super(options);
        this.onChanged_ = null;
        this.prompt_ = null;
        this.isPassword_ = false;

        if (options) {
            if (options.prompt) {
                this.prompt_ = options.prompt;
            }
            if (options.onChanged) {
                this.onChanged_ = options.onChanged;
            }
            if (options.isPassword) {
                this.isPassword_ = options.isPassword;
            }
        }
    }
    onDraw(offx = 0, offy = 0) {
        if (this.prompt_) {
            X2DBeta.drawText(this.prompt_, this.textSize_, this.posX_ + offx, this.posY_ + this.posH_ / 2 + offy, 1, 1, 0, -3, -2, this.textColor_);
        }
        if (this.isPassword_) {
            let str = "";
            for (let i = 0; i < this.name_.length; i++) {
                str += "*";
            }
            X2DBeta.drawText(str, this.textSize_, this.posX_ + this.posW_ / 2 + offx, this.posY_ + this.posH_ / 2 + offy, 1, 1, 0, -2, -2, this.textColor_);
        }
        else {
            X2DBeta.drawText(this.name_, this.textSize_, this.posX_ + this.posW_ / 2 + offx, this.posY_ + this.posH_ / 2 + offy, 1, 1, 0, -2, -2, this.textColor_);
        }
        X2DBeta.drawLine(this.posX_ + offx, this.posY_ + this.posH_ + offy, this.posX_ + this.posW_ + offx, this.posY_ + this.posH_ + offy, this.textColor_);
    }
    onTouch(msg, x, y) {
        if (super.onTouch(msg, x, y)) {
            if (this.clicked_) {
                this.clicked_ = false;
                TextEditor.NormalTextInput.Reset(this.posX_ + XStat.OFFX,
                    this.posY_ + XStat.OFFY,
                    this.posW_,
                    this.posH_,
                    this.name_, (pn) => {
                        this.name_ = pn;
                        if (this.onChanged_) {
                            this.onChanged_(this.name_);
                        }
                    })
            }
            return true;
        }
        return false;
    }
}

module.exports = {
    XInput
}